package me.zhengjie.security.authentication;

import me.zhengjie.security.corporationdetails.CorporationDetails;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 携带企业code的token
 */
public class CorporationAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;
    private Object credentials;
    /**
     * 企业code
     */
    private final Object corporation;

    public CorporationAuthenticationToken(Object principal, Object credentials, Object corporation) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.corporation = corporation;
        super.setAuthenticated(false);
    }

    public CorporationAuthenticationToken(Object principal, Object credentials, Object corporation, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        this.corporation = corporation;
        super.setAuthenticated(true);
    }

    public Object getCorporation() {
        return corporation;
    }


    public String getCorporationCode() {
        if (corporation instanceof CorporationDetails) {
            return ((CorporationDetails) corporation).getCorporationCode();
        }

        return corporation.toString();
    }

    @Override
    public Object getPrincipal() {
        return principal;
    }

    @Override
    public Object getCredentials() {
        return credentials;
    }

    public void setCredentials(Object credentials) {
        this.credentials = credentials;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }
}